#include "DLHook.h"

/**
 *  @file DLinkedList.cpp
 */

namespace cppflib
{


DLHook::DLHook(void)
{
    BreakupLink();
}

DLHook::~DLHook(void)
{
}

/**
 *  Unlink itself from the list
 */
void DLHook::BreakupLink()
{
    m_pNext = m_pPrev = NULL;
}

/**
 *  Add itself to head of list
 *
 *  @param[in,out] pHead -- pointer to head of list
 *  @param[in,out] pTail -- pointer to tail of list
 * 
 */
void DLHook::AddEntryToHead(DLHook ** pHead, DLHook ** pTail)
{
    
    if (*pTail == NULL) {
      *pTail = this;
    }

    if (*pHead == NULL) {
      *pHead = this;
    }
    else {
       (*pHead)->m_pPrev = this;
       this->m_pNext = *pHead;
       this->m_pPrev = NULL;
       *pHead = this;
    }

}

/**
 *  Add itself to tail of list
 *
 *  @param[in,out] pHead -- pointer to head of list
 *  @param[in,out] pTail -- pointer to tail of list
 * 
 */
void DLHook::AddEntryToTail(DLHook ** pHead, DLHook ** pTail)
{
    if (*pHead == NULL)
      *pHead = this;

    if (*pTail == NULL) {
      *pTail = this;  
    }
    else {
       (*pTail)->m_pNext = this;
       this->m_pPrev = *pTail;
       this->m_pNext = NULL;
       *pTail = this;
    }

}

/**
 *  Insert itself between the 2 entries
 */
void DLHook::InsertEntry(DLHook * pPrevEntry, DLHook * pNextEntry)
{
    this->m_pPrev = pPrevEntry;
    this->m_pNext = pNextEntry;
    pPrevEntry->m_pNext = this;
    pNextEntry->m_pPrev = this;
}

/**
 *  Get next entry if any
 *
 *  @return pointer to next entry (NULL if no next one)
 */
DLHook * DLHook::GetNextEntry()
{
    return this->m_pNext;    
}

/**
 *  Get previous entry if any
 *
 *  @return pointer to previous entry (NULL if no previous one)
 */
DLHook * DLHook::GetPrevEntry()
{
    return this->m_pPrev;
}

/**
 *  Delete itselft from the list
 * 
 *  @param[in,out] pHead -- pointer to head of list
 *  @param[in,out] pTail -- pointer to tail of list
 * 
 *  @return pointer to itself
 */
DLHook * DLHook::DeleteEntry(DLHook ** pHead, DLHook ** pTail)
{
    DLHook * pPrev, * pNext;

    pPrev = this->m_pPrev;
    pNext = this->m_pNext;

    if (pPrev != NULL) {
       pPrev->m_pNext = this->m_pNext;
    }
    else {
       *pHead = this->m_pNext;
    }

    if (pNext != NULL) {
       pNext->m_pPrev = this->m_pPrev;
    }     
    else {
       *pTail = this->m_pPrev;
    }  

    // clear at last
    BreakupLink();


	return this;
}


} // end of namespace cppflib

